package com.yl.drug_management.config;

import com.ruoyi.common.core.utils.StringUtils;
import com.yl.drug_management.mapper.CronMapper;
import com.yl.drug_management.utils.CacheKey;
import com.yl.drug_management.utils.RedisBloomUtil;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;

@Configuration
@EnableScheduling
public class SpringTaskConfig implements SchedulingConfigurer {

    /* 动态添加任务参考
    * https://juejin.cn/post/7013234573823705102
    * */

    @Autowired
    CronMapper cronMapper;

    @Autowired
    RedisBloomUtil redisBloomUtil;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> {
                    System.out.println("执行定时任务1: " + LocalDateTime.now().toLocalTime());
                    redisBloomUtil.bfadd(CacheKey.BLOOM_KEY.toString(), cronMapper.getSid());
                },
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    String cron = cronMapper.getCron();
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );

    }
}
